﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Linq.Expressions;

public partial class ListArticles : System.Web.UI.Page
{
    protected PagedDataSource pds = new PagedDataSource();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            CmsDataContext db = new CmsDataContext();
            #region 绑定栏目
            var q = from aT in db.Topic
                    orderby aT.Name
                    select new { ID = aT.ID, Name = aT.Name };
            Topics.DataSource = q.ToList();
            Topics.DataTextField = "Name";
            Topics.DataValueField = "ID";
            Topics.DataBind();

            Topics.Items.Insert(0, new ListItem("全部栏目", ""));
            #endregion
            
            BindData();
        }
    }

    private void BindData()
    {
        //获取文章的原则：文章管理员、审核员登陆后，只能显示本单位的发布文章的情况
        CmsDataContext db = new CmsDataContext();
        var q = from aA in db.Article
                select aA;

        //如果是文章管理员，则只能查看其本单位的信息
        if (Toolkit.HasPower(Powers.ArticleManager))
        {
            q = q.Where(aA => aA.Belong == Toolkit.CurrentUserBelong);
        }
                
        #region 设置所选栏目
        if (Topics.SelectedValue != "")
        {
            q = q.Where(aA => aA.TopicID == Topics.SelectedValue);
        }
        #endregion

        #region 设置检索条件
        string search = SearchConditionHidden.Value.Trim();
        if (search != "")
        {
            Expression<Func<Article, bool>> lmbda = PredicateBuilder<Article>.CreatePredicate(new string[] { "Title", "Subtitle", "Keywords", "Body" }, search, "aA");
            q = q.Where(lmbda);
        }
        #endregion

        var p = q.Select(aA => new
        {
            ID = aA.ID,
            Title = aA.Title,
            Subtitle = aA.Subtitle,
            TopicID = aA.TopicID,
            TopicName = aA.Topic.Name,
            CreatorName = aA.Creator.Name,
            VerifierName = aA.Verifier.Name,
            Published = aA.Published,
            Verified = aA.Verified,
            Keywords = aA.Keywords,
            Body = aA.Body,
            Url = aA.Url,
            Description = aA.Thumbnail
        }).OrderByDescending(aA => aA.Published);


        pds = new PagedDataSource();
        pds.AllowPaging = true;
        pds.PageSize = Toolkit.PageSize;
        pds.DataSource = p.ToList();


        #region 获取当前要显示的页
        int pageIndex = 0;
        pageIndex = Convert.ToInt32(CurrentPage.Value) - 1;
        if (pageIndex >= pds.PageCount)
        {
            pageIndex = pds.PageCount - 1;
        }
        if (pageIndex <= 0)
        {
            pageIndex = 0;
        }
        #endregion

        pds.CurrentPageIndex = pageIndex;

        ArticlesView.DataSource = pds;
        ArticlesView.DataBind();

        CurrentPage.Value = Convert.ToString(pageIndex + 1);
        SearchCondition.Text = SearchConditionHidden.Value.Trim();
    }

    protected void ChangePage(object sender, CommandEventArgs e)
    {
        string kind = Convert.ToString(e.CommandArgument);
        int p = Convert.ToInt32(CurrentPage.Value);

        if (kind == "F")
        {
            CurrentPage.Value = "1";
        }
        else if (kind == "P")
        {
            p--;
            CurrentPage.Value = Convert.ToString(p);
        }
        else if (kind == "N")
        {
            p++;
            CurrentPage.Value = Convert.ToString(p);
        }
        else if (kind == "L")
        {
            CurrentPage.Value = Convert.ToString(Int32.MaxValue);
        }
        else if (kind == "G")
        {
            TextBox gtp;
            foreach (Control c in  ArticlesView.Controls)
            {
                gtp = c.FindControl("GotoPage") as TextBox;
                if (gtp != null)
                {
                    try
                    {
                        CurrentPage.Value = Convert.ToString(Convert.ToInt32(gtp.Text.Trim()));
                    }
                    catch
                    {
                        //CurrentPage.Value = "1";
                    }

                    break;
                }
            }
        }

        BindData();
    }

    protected void DeleteArticle_Click(object sender, EventArgs e)
    {
        string tids = Request.Params["chkID"];
        if (tids != null && tids!="")
        {
            string[] ids = tids.Split(',');
            CmsDataContext db = new CmsDataContext();

            var atcs = from aA in db.Article
                    where ids.Contains(aA.ID)
                    select aA;

            foreach (Article a in atcs)
            {
                string file;

                #region 删除培训对应的栏目
                foreach (Train t in a.Train)
                {
                    t.ArticleID = null;
                }
                #endregion

                #region 删除文章附件及其对应的文件
                foreach (Annex an in a.Annex)
                {
                    file = Toolkit.MappingPath(string.Format("{0}/{1}", Toolkit.PathOfUpload, a.Url));
                    if (File.Exists(file))
                    {
                        File.Delete(file);
                    }

                    db.Annex.DeleteOnSubmit(an);
                }
                #endregion

                #region 删除静态Html文件
                file = Toolkit.MappingPath(string.Format("{0}/{1}",Toolkit.PathOfArticle, a.Url));
                if (File.Exists(file))
                {
                    File.Delete(file);
                }
                #endregion

                #region 删除文章记录
                db.Article.DeleteOnSubmit(a);
                #endregion
            }

            //提交数据库更新
            db.SubmitChanges();

            MessageBox.Message = "所选文章已删除。";
        }

        //重新绑定数据
        BindData();
    }

    protected void Search_Click(object sender, EventArgs e)
    {
        SearchConditionHidden.Value = SearchCondition.Text.Trim();
        BindData();
    }
    protected void Topics_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindData();
    }
    protected void StaticArticles_Click(object sender, EventArgs e)
    {
        CmsDataContext db = new CmsDataContext();
        var q = from aA in db.Article
                select aA;

        if (Toolkit.HasPower(Powers.ArticleManager))
        {
            q = q.Where(aA => aA.District == Toolkit.CurrentUserDistrict && aA.Belong == Toolkit.CurrentUserBelong);
        }

        DateTime dt;
        int year;
        int month;
        try
        {
            foreach (Article a in q)
            {
                dt = a.Published;
                year = dt.Year;
                month = dt.Month;

                a.Url = string.Format("{0}/{1}/{2}.html", year, month, a.ID);

                Toolkit.StaticArticle(a.Url, a.Template);
            }

            db.SubmitChanges();

            MessageBox.Message = "已经静态化全部文章。";
            MessageBox.Location = "./ListArticles.aspx";
        }
        catch (Exception ee)
        {
            MessageBox.Message = "静态化文章时发生错误，请稍后重试。";
        }
    }
}